﻿package com.everydayflash.bitmap {
	
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class ScrollBitmapData extends BitmapData {

		private var source:BitmapData;
		private var zero:Point = new Point(0, 0);
		
		private var dx:int;
		private var dy:int;
		private var w:int;
		private var h:int;
		
		public function ScrollBitmapData(width:int, height:int, transparent:Boolean = true, fillColor:uint = 0xFFFFFFFF) {
			super(width, height, transparent, fillColor);
			dx = 0;
			dy = 0;
		}
		
		public function setSource(source:BitmapData):void {
			this.source = source;
			w = source.width;
			h = source.height;
			copyPixels(source, source.rect, zero);
		}
		
		public function scrollBy(x:Number, y:Number):void {
			lock();
			
			//dx = (dx + x) % w;
			//if (dx < 0) dx = w - dx;
			//copyPixels(source, new Rectangle(dx, 0, w, h), zero);
			//copyPixels(source, new Rectangle(0, 0, dx, h), new Point(w - dx, 0));

			if (x > 0) {
				copyPixels(source, new Rectangle(x, 0, width, height), zero);
				copyPixels(source, new Rectangle(0, 0, x, height), new Point(width-x, 0));
				source.copyPixels(this, rect, zero);
			} else if (x < 0) {
				x = Math.abs(x);
				copyPixels(source, new Rectangle(width-x, 0, x, height), zero);
				copyPixels(source, new Rectangle(0, 0, width-x, height), new Point(x, 0));
				source.copyPixels(this, rect, zero);
			}

			//dy = (dy + y) % h;
			//if (dy < 0) dy = h - dy;
			//copyPixels(source, new Rectangle(0, dy, w, h), zero);
			//copyPixels(source, new Rectangle(0, 0, w, dy), new Point(0, h-dy));
			
			if (y > 0) {
				copyPixels(source, new Rectangle(0, y, width, height), zero);
				copyPixels(source, new Rectangle(0, 0, width, y), new Point(0, height-y));
				source.copyPixels(this, rect, zero);
			} else if (y < 0) {
				y = Math.abs(y);
				copyPixels(source, new Rectangle(0, height-y, width, y), zero);
				copyPixels(source, new Rectangle(0, 0, width, height-y), new Point(0, y));
				source.copyPixels(this, rect, zero);
			}
			
			unlock();
			
		}
	}
}